export const keyCodes = {
  esc: 27,
  space: 32,
  enter: 13,
  tab: 9,
  up: 38,
  down: 40,
  home: 36,
  end: 35,
  n: 78,
  p: 80,
}

export function isObject(value: any) {
  const type = typeof value
  return value != null && (type === 'object' || type === 'function')
}

export function getTarget(target: string, allElements: boolean) {
  const els = findDOMElements(target)
  if (allElements) {
    if (isArrayOrNodeList(els)) {
      return els
    }
    if (els === null) {
      return []
    }
    return [els]
  } else {
    if (isArrayOrNodeList(els)) {
      return els[0]
    }
    return els
  }
}

export function isArrayOrNodeList(els: any) {
  if (els === null) {
    return false
  }
  return Array.isArray(els) || (canUseDOM && typeof els.length === 'number')
}

export function findDOMElements(target: string) {
  if (typeof target === 'string' && canUseDOM) {
    let selection = document.querySelectorAll(target)
    if (!selection.length) {
      selection = document.querySelectorAll(`#${target}`)
    }
    if (!selection.length) {
      throw new Error(
        `The target '${target}' could not be identified in the dom, tip: check spelling`,
      )
    }
    return selection
  }
  return target
}

export const canUseDOM = !!(
  typeof window !== 'undefined' &&
  window.document &&
  window.document.createElement
)

export function isInDOMSubtrees(element: any, subtreeRoots: any[] = []) {
  return (
    subtreeRoots &&
    subtreeRoots.length &&
    subtreeRoots.find((subTreeRoot) => isInDOMSubtree(element, subTreeRoot))
  )
}

export function isInDOMSubtree(element: any, subtreeRoot: any) {
  return subtreeRoot && (element === subtreeRoot || subtreeRoot.contains(element))
}

export function deleteChildren(props: any) {
  let newProps = {...props}
  delete newProps.children
  return newProps
}

export function isEmpty(value: number | string): boolean {
  return value === undefined || value === null
}
